package com.heartbridge.qrcode;

import com.google.zxing.Dimension;
import com.github.heartbridge.fs.annotation.Handler;
import com.github.heartbridge.fs.annotation.RequestMapping;
import com.github.heartbridge.fs.annotation.RequestMethod;
import com.github.heartbridge.fs.annotation.RequestParam;
import com.github.heartbridge.fs.server.ServerStartParamsAware;
import com.github.heartbridge.fs.utils.WebResponse;
import com.heartbridge.qrcode.util.FileUtils;
import com.heartbridge.qrcode.util.QRCode;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;

/**
 * @author GavinCook
 * @since 1.0.0
 **/
@Handler
public class QRCodeHandler implements ServerStartParamsAware {

    private String baseDir;

    @RequestMapping(value = "/qrcode", method = RequestMethod.GET)
    public WebResponse generateCQRode(@RequestParam("content")String content, @RequestParam("imagePath")String imagePath,
                               @RequestParam("text")String text, @RequestParam(value = "width", defaultValue = "300")int width,
                               @RequestParam(value = "height", defaultValue = "300")int height){
        try {
            File file = new File(FileUtils.getTimestampPath(baseDir), System.currentTimeMillis() + ".jpg");
            file = FileUtils.getFileNotExists(file);
            FileUtils.createIfNotExists(file.getAbsolutePath(), false);
            FileOutputStream outputStream = new FileOutputStream(file);
            QRCode.generateQRCodeWithImageAndText(content, imagePath, text, outputStream, new Dimension(width, height));
            return WebResponse.success(file.getAbsolutePath().substring(baseDir.length()-1).replaceAll("\\\\","/"));
        }catch (Exception e){
            e.printStackTrace();
            return WebResponse.fail(e.getMessage());
        }
    }

    @Override
    public void setStartParams(Map<String, String> startParams) {
        this.baseDir = startParams.get(ServerStartParamsAware.BASEDIR);
    }
}
